package cn.itsource.controller;

import cn.itsource.domain.Admin;
import cn.itsource.exception.BusinessExcpetion;
import cn.itsource.mapper.AdminMapper;
import cn.itsource.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 跳转登录页面-跳转功能
     *
     * @return
     */
    @GetMapping("/login")
    public String tologin() {
        return "login";
    }

    /**
     * 登录操作
     *
     * @param username 用户名
     * @param password 密码
     * @param session  把admin类的数据存放session中
     * @param model    向页面传值
     * @return
     */

    @PostMapping("/login")
    public String login(String username, String password, HttpSession session, Model model) {
        try {
            Admin admin = adminService.findusername(username, password);
            //登录成功的业务：将登录信息存放在session中，把password设置为空。
            //admin.setPassword(null);
            session.setAttribute("ADMIN_ID_SESSION", admin);//在前端主页需要显示数据-存放在session中方便取。
            return "index";
        } catch (BusinessExcpetion e) {
            //用户名或者密码错误跳回登录页面。并携带错误信息：e.getMessage()
            model.addAttribute("error", e.getMessage());
            return "login";
        } catch (Exception e) {
            e.printStackTrace(); //打印出错信息
            model.addAttribute("error", "系统繁忙，请稍后再试！！！");
            return "login";
        }
    }

    /**
     * 退出
     *
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();  //删除session中的数据
        return "login";
    }

    /**
     * 跳转修改密码页面
     *
     * @return
     */
    @RequestMapping("/topass")
    public String topass() {
        return "password";
    }

    //修改密码
    @RequestMapping("/uppass")
    public String uppass(@RequestParam("oldPassword") String oldPassword,
                         @RequestParam("newPassword") String newPassword,
                         @RequestParam("reNewPassword") String reNewPassword,
                         HttpSession session,Model model
    ) {
        Admin adminse = (Admin)session.getAttribute("ADMIN_ID_SESSION");
        try {
          //判断password 新密码和旧密码
            Admin admin = adminService.uppassword(adminse, oldPassword, newPassword, reNewPassword);
            return "login";
        }catch (BusinessExcpetion e){
            model.addAttribute("errorpass", e.getMessage());  //用密码错误。并携带错误信息：e.getMessage()
            return "password";
        }
    }
}
